import 'package:flutter/material.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import '../../manger/cached_image_widget.dart';
import '../../components/quantity_selector.dart';
import '../../components/toast_utils.dart';
import '../../manger/user_manger.dart';
import '../../models//home_init_model.dart';
import '../../manger/checkspu_utils.dart';
import '../../components/custom_dialog.dart';
import '../../class/controller/confirm_page.dart';
import '../../models/serach_info_model.dart'; 

class SDetailTopView extends StatefulWidget {
  final CurrencyListModel? selectedCurrency;
  final List<TypeListModel> typeListModel;
  final ValueChanged<String> onSearch;  // 修改为接受 String 参数
  final VoidCallback onBack;
  final bool isUnfold;
  final bool isDataLoaded;
  final ValueChanged<bool> onUnfold;
  final String searchKey;

  SDetailTopView({
    Key? key,
    required this.typeListModel,
    required this.onSearch,
    required this.onBack,
    required this.onUnfold,
    required this.isUnfold,
    required this.isDataLoaded,
    this.selectedCurrency,
    required this.searchKey,
  }) : super(key: key);

  @override
  _SDetailTopViewState createState() => _SDetailTopViewState();
}

class _SDetailTopViewState extends State<SDetailTopView> {
  bool isUnfold = false;
  int selectPath = 0;
  int selectIndex = 0;
  int productNum = 1;
  bool isEnabled = true;
  
  @override
  void didUpdateWidget(SDetailTopView oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.isDataLoaded != oldWidget.isDataLoaded) {
      // 在这里处理isDataLoaded参数变化的逻辑
      setState(() {
        isEnabled = widget.isDataLoaded;
      });
    }
  }

  final TextEditingController searchController = TextEditingController();
  
  @override
  void initState() {
    super.initState();
    searchController.text = widget.searchKey;
    // 初始化监听
    if (widget.selectedCurrency != null) {
      // 使用setState直接响应参数变化
      setState(() {});
    }
  }

  void handleSearch() {
    String searchText = searchController.text.trim();
    
    if (searchText.isEmpty) {
      ToastUtils.showCenterToast(context, AppLocalizations.of(context)!.notempty);
      return;
    }

    // 调用传入的 onSearch 回调并传递搜索内容
    widget.onSearch(searchText);
  }


  @override
  Widget build(BuildContext context) {
    if (widget.typeListModel == null || widget.typeListModel.isEmpty || 
        widget.typeListModel[0].spuList == null || widget.typeListModel[0].spuList.isEmpty) {
      return Center(child: CircularProgressIndicator());
    }
    
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Color(0xFFE1ECFE), Color(0xFFE7E5FD), Color(0xFFF8F6F7)],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
      ),
      padding: const EdgeInsets.only(left: 0, right: 0, top: 50, bottom: 10),
      child: Column(
        children: [
          Row(
            children: [
              IconButton(
                icon: Image.asset('assets/images/leftpush.png',height: 20,width: 20),
                onPressed: widget.onBack,
              ),
              Expanded(
                child: Container(
                  height: 40,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 10),
                        child: Image.asset('assets/images/serach2.png', width: 16, height: 16),
                      ),
                      Expanded(
                        child: TextField(
                          style: TextStyle(
                            color: Color(0xFF505050),
                            fontSize: 14,
                            height: 1.2
                          ),
                          decoration: InputDecoration(
                            isDense: true,
                            hintText: AppLocalizations.of(context)!.pleaseEnterProduct,
                            
                            hintStyle: TextStyle(
                              color: Color(0xFFACACAC),
                              fontSize: 14,
                              height: 1.2
                            ),
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.zero,
                          ),
                          controller: searchController,
                          onSubmitted: (_) => handleSearch(),
                        ),
                      ),
                      SizedBox(width: 5),
                      Container(width: 1, height: 24, color: Color(0xFFE6E6E6), padding: EdgeInsets.zero),
                      TextButton(
                        onPressed: handleSearch,
                        child: Text(AppLocalizations.of(context)!.search, style: TextStyle(color: Colors.blue, fontSize: 14)),
                      ),
                    ],
                  ),
                ),
              ),
              SizedBox(width: 10),
          TextButton(
            onPressed: () {
              setState(() {
                isUnfold = !isUnfold;
              });
              widget.onUnfold(isUnfold);
            },
            style: TextButton.styleFrom(
              backgroundColor: Colors.white,
              shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
              padding: EdgeInsets.symmetric(horizontal: 5),
              fixedSize: Size(60, 35),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                // Bug fix: Add conditional access operator
                Text(UserInfos.shared.currencyListModel?.code ?? 'USD', style: TextStyle(color: Color(0xFF000000), fontSize: 14)),
                SizedBox(width: 2),
                Image.asset(widget.isUnfold ? 'assets/images/收起.png' : 'assets/images/展开1.png', width: 14, height: 14),
              ],
            ),
          ),
          SizedBox(width: 12)
        ],
          ),
          SizedBox(height: 5),
          build2(),
    
        ],
      ),
    );
  }

  Widget build2() {
    return Container(
      height: 374,
      width: MediaQuery.of(context).size.width,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Color(0xFFE1ECFE), Color(0xFFE7E5FD), Color(0xFFF8F6F7)],
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
        ),
      ),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(15),
          ),
          child: Column(
            children: [
              Container(
                height: 73,
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Padding(
                      padding: EdgeInsets.only(left: 15, right: 12),
                      child: CachedImage(
                        imageUrl: widget.typeListModel[0].spuList[0].pic,
                        width: 45,
                        height: 45,
                        fit: BoxFit.cover,
                      ),
                    ),
                    Expanded(
                      child: Text(
                        widget.typeListModel[selectPath].spuList[selectIndex].name,
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 17,
                          color: Color(0xFF000000),
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(
                width: double.infinity,
                child: Image.asset("assets/images/lines.png", height: 10, fit: BoxFit.fill),
              ),
              // 分类导航
              Container(
                height: 50,
                padding: EdgeInsets.symmetric(horizontal: 15),
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: widget.typeListModel.length,
                  itemBuilder: (context, index) {
                    return GestureDetector(
                      onTap: () {
                        setState(() {
                          selectPath = index;
                          selectIndex = 0;
                        });
                      },
                      child: Padding(
                        padding: EdgeInsets.symmetric(horizontal: 12,vertical: 5),
                        child: Container(
                          height: 50,
                          alignment: Alignment.center,
                          child: ConstrainedBox(
                            constraints: BoxConstraints(
                              maxWidth: 120,  // 最大宽度为 80，超过部分省略
                            ),
                            child: Text(
                              widget.typeListModel[index].name,
                              maxLines: 1,  // 限制最大显示 1 行
                            overflow: TextOverflow.ellipsis,  // 超出部分省略
                            style: TextStyle(
                              fontSize: selectPath == index ? 18 : 17,
                              color: selectPath == index ? Color(0xFF000000) : Color(0xFF898989),
                            ),
                          ),
                        ),
                      ),
                    ),
                  );
                  },
                )
              ),
              // 属性选择
              Expanded(
                child: Column(
                  children: [
                    Flexible(
                      child: widget.typeListModel[selectPath].spuList.isEmpty 
                        ? Center(child: Text(AppLocalizations.of(context)!.none))
                        : ListView.builder(
                            padding: EdgeInsets.only(top: 5, bottom: 5, left: 15, right: 5),
                            scrollDirection: Axis.horizontal,
                            itemCount: widget.typeListModel[selectPath].spuList.length,
                            itemBuilder: (context, index) {
                              final model = widget.typeListModel[selectPath].spuList[index];
                              return GestureDetector(
                                onTap: () {
                                  setState(() {
                                    selectIndex = index;
                                  });
                                },
                                child: Container(
                                  height: 90,
                                  constraints: BoxConstraints(minWidth: 80),
                                  margin: EdgeInsets.only(right: 10),
                                  padding: EdgeInsets.symmetric(horizontal: 5),
                                  decoration: BoxDecoration(
                                    color: selectIndex == index ? Color(0xFFF3F6FF) : Colors.white,
                                    borderRadius: BorderRadius.circular(10),
                                    border: Border.all(
                                      color: selectIndex == index ? Color(0xFF5D5FEE) : Color(0xFFE6E6E6),
                                      width: 1,
                                    ),
                                  ),
                                  child: IntrinsicWidth(  // 保证宽度适应内容
                                    child: Column(
                                      mainAxisAlignment: MainAxisAlignment.start,
                                      crossAxisAlignment: CrossAxisAlignment.stretch,
                                      children: [
                                        // 第一部分：model.tag
                                        Container(
                                          height: 20, // 固定高度占位
                                          child: Align(
                                            alignment: Alignment.topRight,  // 右上角对齐
                                            child: model.tag.isNotEmpty ? Container(
                                                padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                                                decoration: BoxDecoration(
                                                  color: Color(0xFFF61F03),
                                                  borderRadius: BorderRadius.only(
                                                    bottomLeft: Radius.circular(10),
                                                    topRight: Radius.circular(10),
                                                  ),
                                                ),
                                                child: Text(
                                                  model.tag ,
                                                  style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: 10,
                                                    height: 1.2,
                                                    fontWeight: FontWeight.w500,
                                                  ),
                                                  maxLines: 1,
                                                  overflow: TextOverflow.ellipsis,
                                                ),
                                              ) : Container(height: 20, color: Colors.transparent),
                                          ),
                                        ),
                                        // 第二部分：model.attrvalue
                                        Container(
                                          height: 25,
                                          alignment: Alignment.center,
                                          child: Text(
                                            model.attrvalue,
                                            style: TextStyle(
                                              fontSize: 14,
                                              color: selectIndex == index ? Color(0xFF5D5FEE) : Color(0xFF000000),
                                            ),
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ),
                                        // 第三部分：model.priceFee
                                        Container(
                                          height: 25,
                                          alignment: Alignment.center,
                                          child: Text(
                                            '${model.symbol}${model.priceFee}',
                                            style: TextStyle(
                                              fontSize: 14,
                                              color: Color(0xFFF61F03),
                                              height: 1.2,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              );
                            },
                          ),
                    ),
                    SizedBox(
                      height: 120,
                      child: build3(),
                    ),
                  ],
                ),
              )



            ],
            
          ),
        ),
      ),
    );
  }

  Widget build3() {
  if (widget.typeListModel.isEmpty || widget.typeListModel[selectPath].spuList.isEmpty) {
    return Container();
  }
  final model = widget.typeListModel[selectPath].spuList[selectIndex];

  return Column(
    children: [
      Padding(
        padding: const EdgeInsets.symmetric(vertical: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Padding(
              padding: const EdgeInsets.only(left: 13),
              child: RichText(
                text: TextSpan(
                  children: [
                    TextSpan(
                      text: AppLocalizations.of(context)!.totalPrice,
                      style: TextStyle(
                        color: const Color(0xFF666666),
                        fontSize: 14,
                      ),
                    ),
                    TextSpan(
                      text: '${model.symbol}${(productNum * double.parse(model.priceFee)).toStringAsFixed(2)}',
                      style: TextStyle(
                        color: const Color(0xFFF61F03),
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(right: 12),
              child: QuantitySelector(
                onChanged: (value) => setState(() => productNum = value),
              ),
            ),
          ],
        ),
      ),
      Container(
        width: MediaQuery.of(context).size.width * 0.8,
        height: 38,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(19),
          gradient: const LinearGradient(
            colors: [Color(0xFF5F60EF), Color(0xFF8A9CFF)],
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
          ),
          boxShadow: [
            BoxShadow(
              color: const Color(0xFF5D5FEE).withValues(alpha:  0.3),
              blurRadius: 10.3,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child: MaterialButton(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(19),
          ),
          onPressed: () {
            checkspu(context);
          },
          child: Text(
            AppLocalizations.of(context)!.buyNow,
            style: TextStyle(
              color: Colors.white,
              fontSize: 15,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
    ],
  );
}

  // 检查商品是否可以购买
  Future<void> checkspu(BuildContext context) async {

    if (!isEnabled){
      return;
    }
    ToastUtils.showLoadingToast(context);
    final result = await CheckSpuConfig().checkSpuConfigWithId(widget.typeListModel[selectPath].spuList[selectIndex].spuId.toString());
    if (result) {
      final result2 = await CheckSpuConfig().checkMaxcoinWithId(widget.typeListModel[selectPath].spuList[selectIndex].spuId, productNum);
      ToastUtils.dismissLoadingToast();
      if (result2['success']) {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => ConfirmPage(
            selectedModel: widget.typeListModel[selectPath].spuList[selectIndex],pricenum: productNum,producttype: widget.typeListModel[selectPath].name)),
        );
      }else{
        _showLogoutDialog(context,result2['message']);
      }
      // 处理成功逻辑
    } else {
      ToastUtils.dismissLoadingToast();
      _showLogoutDialog(context,AppLocalizations.of(context)!.valueReachedLimitr);
    }
  }

  void _showLogoutDialog(BuildContext context,String desc) {
    showDialog(
      context: context,
      builder: (context) => CustomDialog(
        title: AppLocalizations.of(context)!.orderfail,
        description: desc,
        leftButtonText: AppLocalizations.of(context)!.cancel,
        rightButtonText: AppLocalizations.of(context)!.confirm,
        onLeftPressed: () => Navigator.pop(context),
        onRightPressed: () {
          Navigator.pop(context);
        },
      ),
    );
  }
}

